package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.application.SmartRobotApplication;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.huanxinapi.activity.Constant;
import com.huanxinapi.activity.UserDao;
import com.smartrobot.smartrobot.Common.CommonFunc;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageUtil;
import com.smartrobot.smartrobot.util.PeopleRegisterMsg;
import com.smartrobot.smartrobot.util.PictureFromCammera;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RegisterActivity extends Activity implements OnClickListener {

    private ImageView imgBack, imgPhoto, imgReadHead;
    private RelativeLayout register;
    private TextView getIdentifyNum;
    private TextView readPosition, progressTxt;
    private EditText phone, identifyNum, password, surePassword, organ, masterNum;
    private LinearLayout detail, progressLayout;
    private ProgressBar progressBar;

    private PeopleRegisterMsg user = null;
    private String path;
    private boolean isGetMessage = false;
    private RegisterHandler handler = new RegisterHandler();
    private final int LONGIN_HUANXIN_OK = 1113;
    private final int LONGIN_HUANXIN_FAILD = 1114;

    private boolean isRegisting = false;
    private boolean isPressRegister = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }

        SmartRobotApplication.getInstance().logout(null);
        HttpUtil.init(getApplicationContext());
        if (this.getIntent() != null && this.getIntent().getIntExtra("role", 1) == 0) {
            this.setContentView(R.layout.page_register_hairdreser);
            initRegister();
        } else {
            this.setContentView(R.layout.page_register_user);
            initUser();
        }

    }

    public void initRegister() {


        imgBack = (ImageView) findViewById(R.id.hairdreser_back);
        imgPhoto = (ImageView) findViewById(R.id.hairdreser_photo);
        getIdentifyNum = (TextView) findViewById(R.id.hairdreser_getIdnetifyNum);
        register = (RelativeLayout) findViewById(R.id.hairdreser_register);
        phone = (EditText) findViewById(R.id.hairdreser_phone);
        identifyNum = (EditText) findViewById(R.id.hairdreser_identifyNum);
        password = (EditText) findViewById(R.id.hairdreser_password);
        surePassword = (EditText) findViewById(R.id.hairdreser_sure_password);
        organ = (EditText) findViewById(R.id.hairdreser_organ);
        masterNum = (EditText) findViewById(R.id.hairdreser_master_account);
        detail = (LinearLayout) findViewById(R.id.hairdreser_read_detail);
        imgReadHead = (ImageView) findViewById(R.id.hairdreser_read_detail_head);
        readPosition = (TextView) findViewById(R.id.hairdreser_read_detail_position);
        progressLayout = (LinearLayout) findViewById(R.id.register_progresslayout);
        progressBar = (ProgressBar) findViewById(R.id.register_progressbar);
        progressTxt = (TextView) findViewById(R.id.register_txt);


        imgBack.setOnClickListener(this);
        imgPhoto.setOnClickListener(this);
        imgPhoto.setImageDrawable(this.getResources().getDrawable(R.drawable.dhead_icon));

//		phone.setText("18925963333");
//		password.setText("123456");
//		surePassword.setText("123456");
//		organ.setText("2222");
//		masterNum.setText("18925962222");


        getIdentifyNum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                identifyNum.setText("123456");

            }
        });

//        findOrgan.setVisibility(View.GONE);
//        findOrgan.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//
//				if(organ.getText().toString().length() > 0 && organ.getText().toString().length() <= 20
//						&& masterNum.getText().toString().length() == 11){
//					if(!isGetMessage){
//						detail.setVisibility(View.VISIBLE);
//						isGetMessage = true;
//					}
//
//				}
//
//			}
//		});

        register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                switch (legalLoginHairReset()) {

                    case 1:
                        ToastCustom.showToast(getApplicationContext(), "账号不能为空和最大为20位");
                        break;
                    case 2:
                        ToastCustom.showToast(getApplicationContext(), "验证码有误");
                        break;
                    case 3:
                        ToastCustom.showToast(getApplicationContext(), "密码为6-12位");
                        break;
                    case 4:
                        ToastCustom.showToast(getApplicationContext(), "确认密码和密码不一致");
                        break;
                    case 5:
                        ToastCustom.showToast(getApplicationContext(), "店铺名称和店主账号位数不为空");
                        break;

                    default:
                        user = new PeopleRegisterMsg();
                        user.setPhone(phone.getText().toString().trim());
                        user.setPwd(password.getText().toString().trim());
                        if (path != null && !path.equals(""))
                            user.setHead(path);
                        user.setStoreName(organ.getText().toString().trim());
                        user.setsMasterAccount(masterNum.getText().toString().trim());

                        if (!isRegisting) {
                            isPressRegister = true;
                            isRegisting = true;
                            HttpUtil.apiRegisterHairReset(user, handler);
                            InputMethodManager imm = (InputMethodManager) getSystemService(RegisterActivity.this.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

                            progressLayout.setVisibility(View.VISIBLE);
                            progressTxt.setText("正在加载...");
                        }


                        break;

                }

            }
        });


    }

    int legalLoginHairReset() {

        if (phone.getText().toString().trim().length() < 1 || phone.getText().toString().trim().length() > 20)
            return 1;
        if (identifyNum.getText().toString().trim().length() < 6 || identifyNum.getText().toString().trim().length() > 6)
            return 2;
        if (password.getText().toString().trim().length() < 6 || password.getText().toString().trim().toString().trim().length() > 12)
            return 3;
        if (!password.getText().toString().trim().equals(surePassword.getText().toString().trim()))
            return 4;
        if (organ.getText().toString().trim().length() < 1 || organ.getText().toString().trim().length() > 20
                || masterNum.getText().toString().trim().length() < 1 || masterNum.getText().toString().trim().length() > 20)
            return 5;

        return 10;
    }

    int legalLoginUser() {

        if (phone.getText().toString().trim().length() < 1 || phone.getText().toString().trim().length() > 20)
            return 1;
        if (identifyNum.getText().toString().trim().length() < 6 || identifyNum.getText().toString().trim().length() > 6)
            return 2;
        if (password.getText().toString().trim().length() < 6 || password.getText().toString().trim().length() > 12)
            return 3;
        if (!password.getText().toString().trim().equals(surePassword.getText().toString().trim()))
            return 4;

        return 10;
    }


    void initUser() {//初始化创建user

        imgBack = (ImageView) findViewById(R.id.user_back);
        imgPhoto = (ImageView) findViewById(R.id.user_photo);
        getIdentifyNum = (TextView) findViewById(R.id.user_getIdentifyNum);
        register = (RelativeLayout) findViewById(R.id.user_register);
        phone = (EditText) findViewById(R.id.user_phone);
        identifyNum = (EditText) findViewById(R.id.user_IdentifyNum);
        password = (EditText) findViewById(R.id.user_password);
        surePassword = (EditText) findViewById(R.id.user_sure_password);
        progressLayout = (LinearLayout) findViewById(R.id.register_progresslayout);
        progressBar = (ProgressBar) findViewById(R.id.register_progressbar);
        progressTxt = (TextView) findViewById(R.id.register_txt);


        imgBack.setOnClickListener(this);
        imgPhoto.setOnClickListener(this);
        imgPhoto.setImageDrawable(this.getResources().getDrawable(R.drawable.dhead_icon));
        getIdentifyNum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                identifyNum.setText("123456");

            }
        });


        register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                switch (legalLoginUser()) {//娇艳

                    case 1:
                        ToastCustom.showToast(getApplicationContext(), "账号不能为空和最大为20位");
                        break;
                    case 2:
                        ToastCustom.showToast(getApplicationContext(), "验证码有误");
                        break;
                    case 3:
                        ToastCustom.showToast(getApplicationContext(), "密码为6-12位");
                        break;
                    case 4:
                        ToastCustom.showToast(getApplicationContext(), "确认密码和密码不一致");
                        break;

                    default: {

                        user = new PeopleRegisterMsg();
                        user.setPhone(phone.getText().toString().trim());
                        user.setPwd(password.getText().toString().trim());
                        if (path != null && !path.equals(""))
                            user.setHead(path);

                        if (!isRegisting) {
                            isPressRegister = true;
                            isRegisting = true;
                            HttpUtil.apiRegisterUser(user, handler);

                            InputMethodManager imm = (InputMethodManager) getSystemService(RegisterActivity.this.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

                            progressLayout.setVisibility(View.VISIBLE);
                            progressTxt.setText("正在加载...");

                        }

                    }
                    break;
                }
            }

        });

    }

    @Override
    public void onClick(View v) {//监听点击

        if (v.getId() == imgBack.getId())
        {

            if(isRegisting){
                ToastCustom.showToast(getApplicationContext(),"正在注册登录中，请稍后...");
            }else{
                this.finish();
            }

        }

        if (v.getId() == imgPhoto.getId()) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(RegisterActivity.this);
            dialog.setTitle("选择")
                    .setItems(R.array.photoMenu,
                            new AlertDialog.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    switch (which) {
                                        case 0://通过照相机获取图片
                                            path = ImageUtil.getCameraPic(RegisterActivity.this, ImageUtil.IMAGE_FROM_CAMMERA);
                                            break;
                                        case 1://通过打开文件获取图片
                                            ImageUtil.getDirPic(RegisterActivity.this, ImageUtil.IMAGE_FROM_FILE);
                                            break;
                                    }
                                }
                            }).show();
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            System.out.println("down");
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }

    // 处理返回结果
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ImageUtil.IMAGE_FROM_CAMMERA) {// 通过照相机获取图片
            if (resultCode == RESULT_OK) { // 成功获得图片
                if (path != null && !path.equals("")) {
                    Bitmap headBitmap = PictureFromCammera.scaleBitmap(path);
                    imgPhoto.setImageBitmap(headBitmap);

                    // 头像的名字
                    String fileName = FileUtil.headName;
                    //保存的路径
                    String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                            + fileName;


                    if (FileUtil.createFile(filePath)) {
                        // 将图片保存在文件夹中
                        if (FileUtil.writeBitmapToSDCard(filePath, headBitmap))
                            path = filePath;

//										ToastCustom.showToast(getApplicationContext(), "保存成功");
                    }

                } else
                    ToastCustom.showToast(getApplicationContext(), "无法获取图片，请重新选择");


            }
        }

        if (requestCode == ImageUtil.IMAGE_FROM_FILE) {//打开文件夹获取图片
            if (resultCode == RESULT_OK) { // 成功
                try {
                    Uri uri = data.getData();
                    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    path = cursor.getString(1);
                    cursor.close();
                    if (path != null) {
                        Bitmap headBitmap = PictureFromCammera.scaleBitmap(path);
                        imgPhoto.setImageBitmap(headBitmap);
                        String fileName = FileUtil.headName;
                        String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                                + fileName;


                        if (FileUtil.createFile(filePath)) {
                            // 保存到手机sd卡中，同时缩小图片大小
                            if (FileUtil.writeBitmapToSDCard(filePath, headBitmap))
                                path = filePath;
//										ToastCustom.showToast(getApplicationContext(), "保存成功");
                        }
                    } else
                        ToastCustom.showToast(getApplicationContext(), "无法保存图片，请重新选择");
                } catch (Exception e) {
                    ToastCustom.showToast(getApplicationContext(), "无法找到图片，请重新选择");
                }
            }
        }
    }

    class RegisterHandler extends Handler {

        @Override
        public void dispatchMessage(final Message msg) {

            switch (msg.what) {

                case HttpUtil.LOGIN_SUCCESS:

//                            socketUtil.initSocket_2(getApplicationContext());
                    final String account = User.getInstance().getPhone();
                    final String password = CommonFunc.stringToMD5(account);

                    Log.e("帐号---------------->",account+"   ");

                    // 调用sdk登陆方法登陆聊天服务器
                    EMChatManager.getInstance().login(account, password, new EMCallBack() {

                        @Override
                        public void onSuccess() {

                            // 登陆成功，保存用户名密码
                            SmartRobotApplication.getInstance().setUserName(account);
                            SmartRobotApplication.getInstance().setPassword(password);
                            try {
                                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                                // ** manually load all local groups and
                                // conversations in case we are auto login
                                EMGroupManager.getInstance().loadAllGroups();
                                EMChatManager.getInstance().loadAllConversations();

                                // demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
                                List<String> usernames = EMContactManager.getInstance().getContactUserNames();
                                EMLog.d("roster", "contacts size: " + usernames.size());
                                Map<String, com.huanxinapi.activity.User> userlist = new HashMap<String, com.huanxinapi.activity.User>();
                                for (String username : usernames) {
                                    com.huanxinapi.activity.User user = new com.huanxinapi.activity.User();
                                    user.setUsername(username);
                                    setUserHearder(username, user);
                                    userlist.put(username, user);
                                }
                                // 存入内存
                                SmartRobotApplication.getInstance().setContactList(userlist);
                                // 存入db
                                UserDao dao = new UserDao(RegisterActivity.this);
                                List<com.huanxinapi.activity.User> users = new ArrayList<com.huanxinapi.activity.User>(userlist.values());
                                dao.saveContactList(users);

                                // 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
                                EMGroupManager.getInstance().getGroupsFromServer();
                            } catch (Exception e) {
                                e.printStackTrace();
                                //取好友或者群聊失败，不让进入主页面，也可以不管这个exception继续进到主页面 不处理
                            }
                            //更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                            boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(SmartRobotApplication.currentUserNick.trim());
                            if (!updatenick) {
                                Log.e("LoginActivity", "update current user nick fail");
                            }

                            Message msg = new Message();
                            msg.what = LONGIN_HUANXIN_OK;
                            handler.sendMessage(msg);


                        }

                        @Override
                        public void onProgress(int progress, String status) {
                        }

                        @Override
                        public void onError(final int code, final String message) {

                            Message msg = new Message();
                            msg.what = LONGIN_HUANXIN_FAILD;
                            msg.obj = message;
                            handler.sendMessage(msg);

                        }

                    });


                    break;
//				intent.setClass(LoginActivity.this,MainActivity.class );
//				startActivity(intent);
//				LoginActivity.this.finish();


//					case HttpUtil.LOGIN_SUCCESS:
//
//						ToastCustom.showToast(getApplicationContext(), "登陆");
//						Intent intent = new Intent();
//						intent.setClass(RegisterActivity.this, MainActivity.class);
//						startActivity(intent);
//                        isRegisting = false;
//                        LoginActivity.activity.finish();
//						RegisterActivity.this.finish();
//						break;

                case HttpUtil.REGISTER_HAIRRESET_SUCCESS:
//                    ToastCustom.showToast(getApplicationContext(), "注册成功");
                    progressLayout.setVisibility(View.VISIBLE);
                    progressTxt.setText("注册成功，正在登陆...");
                    HttpUtil.apiLogin(getApplicationContext(), user, handler);

                    break;

                case HttpUtil.REGISTER_USER_SUCCESS:

//                    ToastCustom.showToast(getApplicationContext(), "注册成功");
                    progressLayout.setVisibility(View.VISIBLE);
                    progressTxt.setText("注册成功，正在登陆...");
                    HttpUtil.apiLogin(getApplicationContext(), user, handler);
                        /*
							LayoutInflater inflater = getLayoutInflater();
						    View layout = inflater.inflate(R.layout.page_register_is_group,null);
						    final AlertDialog dialog = new AlertDialog.Builder(RegisterActivity.this).setView(layout).show();
							
						    layout.findViewById(R.id.group_refulse).setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									
									dialog.dismiss();
									HttpUtil.apiLogin(user, handler);
									
								}
							});
						    
						    layout.findViewById(R.id.group_ok).setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									
									dialog.dismiss();
									Intent intent = new Intent();
									intent.setClass(RegisterActivity.this, TakeIngoupActivity.class);
									startActivity(intent);
									
								}
							});
						*/
                    break;

                case HttpUtil.LOGIN_FAILD:

                    progressLayout.setVisibility(View.GONE);
                    isRegisting = false;

                    if(msg.obj != null){
                        if(msg.obj.equals("106"))
                            ToastCustom.showToast(RegisterActivity.this, "账号或密码错误!");
                        else
                            ToastCustom.showToast(RegisterActivity.this, "登陆服务器失败，请稍后再试");
                    }
                    else
                        ToastCustom.showToast(RegisterActivity.this, "登陆服务器失败，请稍后再试");


                    break;

                case HttpUtil.REGISTER_FAILD:

                    if(msg.obj != null){
                        if(msg.obj.equals("2"))
                            ToastCustom.showToast(getApplicationContext(), "账号已存在!");
                        else  if(msg.obj.equals("6"))
                            ToastCustom.showToast(getApplicationContext(), "店铺名称或者店主账号错误!");
                        else
                            ToastCustom.showToast(getApplicationContext(), "连接服务器失败,请稍后再试!");

                    }
                    else
                    ToastCustom.showToast(getApplicationContext(), "连接服务器失败,请稍后再试!");
                    progressLayout.setVisibility(View.GONE);
                    isRegisting = false;

                    break;

                case LONGIN_HUANXIN_OK:

                    if(isPressRegister){
                    isPressRegister = false;
                    User.getInstance().setIsLogin(true);//这就意味着可以跳过登录界面
                    User.saveUserInfo(getApplicationContext());
//                    ToastCustom.showToast(getApplicationContext(), "登陆");
                    Intent intent = new Intent();
                    intent.setClass(RegisterActivity.this, MainActivity.class);
                    startActivity(intent);
                    isRegisting = false;
                    LoginActivity.activity.finish();
                    RegisterActivity.this.finish();
                    }

                    break;

                case LONGIN_HUANXIN_FAILD:

                    isRegisting = false;
                    ToastCustom.showToast(getApplicationContext(), "连接服务器失败,请稍后再试!");
                    progressLayout.setVisibility(View.GONE);
                    Log.e("================>", msg.obj.toString());

                    break;

            }

        }

    }

    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    protected void setUserHearder(String username, com.huanxinapi.activity.User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK){

            if(isRegisting) {
                ToastCustom.showToast(getApplicationContext(),"正在注册登录中，请稍后...");
                return false;
            }

        }

        return super.onKeyDown(keyCode, event);
    }
}


